package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleServiceImpl implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 加载首页
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto , Integer type) {
        //1.参数校验
        if (dto.getSize() == null){
            dto.setSize(10);
        }
        if (dto.getTag() == null){
            dto.setTag("__all__");
        }
        if (dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime() == null){
            dto.setMaxBehotTime(new Date());
        }
        //2.调用mapper接口
        List<ApArticle> articleList = apArticleMapper.load(dto, type);
        //3.封装数据
        return ResponseResult.okResult(articleList);

    }
    /**
     * 加载热点文章数据，从redis,只适用于首页，如果是上拉和下拉则不执行该方法
     *
     * @param dto
     */
    @Override
    public ResponseResult loadFromRedis(ArticleHomeDto dto) {

        String hotArticleListStr = stringRedisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        //转化类型
        List<HotArticleVo> hotArticleVoList = JSONArray.parseArray(hotArticleListStr, HotArticleVo.class);

        return ResponseResult.okResult(hotArticleVoList);
    }







    /**
     * 新增文章三剑客
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult saveAparticle(ArticleDto dto) {
        ApArticle apArticle=new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        //1.判断是否保存还是修改
        if(dto.getId()==null){
            //如果保存的话
            //新增ap_article
            apArticle.setCreatedTime(new Date());
            apArticle.setPublishTime(new Date());
            apArticle.setLikes(0);
            apArticle.setViews(0);
            apArticle.setComment(0);
            apArticle.setCollection(0);
            apArticleMapper.insert(apArticle);
            //新增ap_article_config
            ApArticleConfig aparticleConfig=new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(aparticleConfig);
            //新增ap_article_content
            ApArticleContent apArticleContent=new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }else {
            //如果是修改的话
            //修改ap_article
            apArticleMapper.updateById(apArticle);
            //修改ap_article_content
            ApArticleContent apArticleContent=apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,apArticle.getId()));
            if(apArticleContent!=null){
                apArticleContent.setContent(dto.getContent());
                apArticleContentMapper.updateById(apArticleContent);
            }
        }


        //异步调用生成静态化文件操作
        generatorHtml(apArticle.getId());



        //注意。一定要返回一个文章id，因为我们在文章审核通过之后，要把该articleId写入wmnews表中
        return ResponseResult.okResult(apArticle.getId());
    }



    /**
     * 抽取生成静态化文件并保存到minio中
     * @throws Exception
     */
    @Async
    public void generatorHtml(Long articeId) {
        //1.根据文章id获取文章内容
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articeId));
        if(apArticleContent==null){
            return;
        }
        //2.生成html文件
        //获取模板
        Template template = null;
        try {
            template = configuration.getTemplate("article.ftl");
            //获取数据模型
            Map dataModel=new HashMap();
            dataModel.put("content", JSONArray.parseArray(apArticleContent.getContent()));
            //合成
            StringWriter out=new StringWriter();//定义了字符串写入流，此时为空
            template.process(dataModel,out);
            //此时走完了合成之后，out中就会有数据

            //3.上传文件到minio中
            InputStream is=new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", is);

            //4.修改ap_article表中的static_url字段，保存是静态化文件保存在minio中的路径地址
            ApArticle aparticle=apArticleMapper.selectById(apArticleContent.getArticleId());
            if(aparticle!=null){
                aparticle.setStaticUrl(path);
                apArticleMapper.updateById(aparticle);
            }
            //调用发送消息操作
            createArticleESIndex(aparticle,apArticleContent.getContent());

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    @Resource
    private KafkaTemplate<String,String > kafkaTemplate;

    /**
     * 发送消息到kafka中
     */
    public void  createArticleESIndex(ApArticle apArticle,String content){
        System.out.println("发送文章到es中的方法参数为:"+apArticle.toString()+content);
        /**
         * 思考，从article端传输什么参数给Kafka
         */
        SearchArticleVo vo=new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setLayout(apArticle.getLayout().intValue());
        vo.setContent(content);
        kafkaTemplate.send(WmNewsMessageConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
        System.out.println("发送文章到es中的方法执行了");
    }

}







